-- Radical by Basil Voronkov
-- Module 'tact'
---------------------------------------------
-- This module implements tact handling.
require "lib/core"

tact = {}

function tact.resident() 
  return obj {
     nam        = "tact_resident"
    ,_tactnum   = 0
    ,handlers   = {}
    ,events     = {}
    ,life       = function(s)
                    s._tactnum = s._tactnum + 1;
                    for i,v in pairs(s.handlers) do
                      v(s._tactnum);
                    end
                  end
    ,add        = function(s, key, fun)
                    s.handlers[key] = fun;
                  end
    ,remove     = function(s, key)
                    s.handlers[key] = nil;
                  end
  }
end

function event(o)
  local ret = obj {
     nam        = "event"
    ,invoke     = o.invoke
    ,enable     = function(s)
                    s._enable = true;
                  end
    ,disable    = function(s)
                    s._enable = false;
                  end
  }
  table.insert(tact_resident.events, ret);
  return ret;
end

function tact.init()
  tact_resident = tact.resident();
  tact_resident:add(
    "gameevent",
    function()
      for i,v in ipairs(tact_resident.events) do
        if v._enable and v.invoke ~= nil then
          v:invoke();
        end
      end
    end
  )
  lifeon(tact_resident);
end

